package server

import (
	"fmt"
	"gitee.com/snxamdf/wui/util"
	wdata "gitee.com/snxamdf/wui/util/w"
	"net/http"
	"sync"
	"time"
)

const (
	sessionId = "w_session_id"
)

var gloab_session = sync.Map{}

type session struct {
	id        string
	authorize bool //是否需要授权(登录)
	token     string
	data      *wdata.WMap
}

func (m *session) Set(key string, value interface{}) {
	m.data.Put(key, value)
}

func (m *session) Get(key string) interface{} {
	return m.data.Get(key)
}

func (m *session) auth() {
	m.authorize = true
}

func (m *session) getAuth() bool {
	return m.authorize
}

func (m *session) Id() string {
	return m.id
}

func GetSession(sid string) Session {
	if s, ok := gloab_session.Load(sid); ok {
		return s.(Session)
	}
	return nil
}

func createSession(w http.ResponseWriter, r *http.Request) Session {
	sid := r.Header.Get(sessionId)
	if sid == "" {
		sid, _ = getCookie(r, sessionId)
	}
	if sid == "" {
		sid = util.MD5(fmt.Sprintf("%s-%d", sessionId, time.Now().Nanosecond()))
		setCookie(w, sessionId, sid)
		r.Header.Set(sessionId, sid)
	}
	sess := &session{
		id:        sid,
		authorize: false,
		token:     "",
		data:      wdata.NewMap(),
	}
	gloab_session.Store(sid, sess)
	return sess
}
